﻿namespace MhAdmin.System;

/// <summary>
/// <inheritdoc cref="IRulesLogService"/>
/// </summary>
public class RulesLogService : DbRepository<DevRulesLog>, IRulesLogService
{
    private readonly ILogger<RulesLogService> _logger;
    private readonly ISysUserService _sysUserService;

    public RulesLogService(ILogger<RulesLogService> logger, ISysUserService sysUserService
    )
    {
        _sysUserService = sysUserService;
        _logger = logger;
    }

    #region 查询

    /// <inheritdoc/>
    public async Task<SqlSugarPagedList<RulesLogPageOutput>> Page(RulesLogPageInput input)
    {
        var query = await GetQuery(input);//获取查询条件
        var pageInfo = await query.ToPagedListAsync(input.Current, input.Size);//分页
        return pageInfo;
    }

    /// <inheritdoc/>
    public async Task<List<RulesLogPageOutput>> List(RulesLogPageInput input)
    {
        var query = await GetQuery(input);//获取查询条件
        var list = await query.ToListAsync();
        return list;
    }

    /// <inheritdoc />
    public async Task<DevRulesLog> Detail(BaseIdInput input)
    {
        var rulesLog = await GetFirstAsync(it => it.Id == input.Id);
        var errorMessage = $"您没有权限查看该数据";
        //获取数据范围
        var dataScope = await _sysUserService.GetLoginUserApiDataScope();
        if (dataScope != null && (!dataScope.Contains(rulesLog.CreateOrgId) || rulesLog.CreateUserId != UserManager.UserId))//判断机构ID是否在数据范围或者创建人是否为当前登录人
            throw Oops.Bah(errorMessage);
        return rulesLog;
    }

    //外键查询

    #endregion 查询

    #region 新增

    /// <inheritdoc />
    public async Task Add(RulesLogAddInput input)
    {
        var rulesLog = input.Adapt<DevRulesLog>();//实体转换
        await CheckInput(rulesLog);//检查参数
        //获取数据范围
        var dataScope = await _sysUserService.GetLoginUserApiDataScope();
        //判断机构ID是否在数据范围,这里只是简单示例，根据实际情况判断
        //if (dataScope!=null&&(!dataScope.Contains(rulesLog.OrgId)))
        //throw Oops.Bah("您没有权限添加该数据");
        await InsertAsync(rulesLog);//插入数据
    }

    #endregion 新增

    #region 编辑

    /// <inheritdoc />
    public async Task Edit(RulesLogEditInput input)
    {
        var rulesLog = input.Adapt<DevRulesLog>();//实体转换
        await CheckInput(rulesLog);//检查参数
                                   //判断机构ID是否在数据范围并且创建者是自己,这里只是简单示例，根据实际情况判断
                                   //if (dataScope!=null&&(!dataScope.Contains(rulesLog.CreateOrgId) || rulesLog.CreateUserId != UserManager.UserId))
                                   //throw Oops.Bah("您没有权限编辑该数据");
        await UpdateAsync(rulesLog);//更新数据
    }

    #endregion 编辑

    #region 删除

    /// <inheritdoc />
    public async Task Delete(List<BaseIdInput> input)
    {
        //获取所有ID
        var ids = input.Select(it => it.Id).ToList();
        if (ids.Count > 0)
        {
            //获取数据范围
            var dataScope = await _sysUserService.GetLoginUserApiDataScope();
            var rulesLogs = await GetListAsync(it => ids.Contains(it.Id), it => new DevRulesLog { CreateOrgId = it.CreateOrgId, CreateUserId = it.CreateUserId });//根据ID获取机构ID和创建者ID
            rulesLogs.ForEach(it =>
            {
                if (dataScope != null && !dataScope.Contains(it.CreateOrgId) && it.CreateUserId != UserManager.UserId) throw Oops.Bah(ErrorCodeEnum.A0004);//如果不包含机构id并且不是自己创建的
            });
            await DeleteByIdsAsync(ids.Cast<object>().ToArray());//删除数据
                                                                 ////事务
                                                                 //var result = await itenant.UseTranAsync(async () =>
                                                                 //{
                                                                 //await DeleteByIdsAsync(ids.Cast<object>().ToArray());//删除数据
                                                                 //});
                                                                 //if (!result.IsSuccess)//如果成功了
                                                                 //{
                                                                 ////写日志
                                                                 //_logger.LogError(result.ErrorMessage, result.ErrorException);
                                                                 //throw Oops.Oh(ErrorCodeEnum.A0002);
                                                                 //}
        }
    }

    #endregion 删除



    #region 方法

    /// <summary>
    /// 检查输入参数
    /// </summary>
    /// <param name="rulesLog"></param>
    private async Task CheckInput(DevRulesLog rulesLog)
    {
        var errorMessage = $"您没有权限操作该数据";
        if (rulesLog.Id == MhAdminConst.Zero)
        {
            //表示新增
        }
        else
        {
            //表示编辑
        }
    }

    /// <summary>
    /// 获取Sqlsugar的ISugarQueryable
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    private async Task<ISugarQueryable<RulesLogPageOutput>> GetQuery(RulesLogPageInput input)
    {
        //获取数据范围
        var dataScope = await _sysUserService.GetLoginUserApiDataScope();
        //动态查询条件,如果是连表查询,里面的it要改成连表里对应的别名
        var exp = Expressionable.Create<DevRulesLog>();
        exp.AndIF(dataScope is { Count: > 0 }, it => dataScope.Contains(it.CreateOrgId));//用户机构在数据范围内
        exp.AndIF(dataScope is { Count: 0 }, it => it.CreateUserId == UserManager.UserId);//默认创建者ID等于自己,根据实际情况修改条件
        var query = Context.Queryable<DevRulesLog>()
                         .LeftJoin<DevRules>((it, y) => it.RuleCode == y.RuleCode)
                         .WhereIF(!string.IsNullOrWhiteSpace(input.RuleCode), it => it.RuleCode.Contains(input.RuleCode.Trim()))
                          .WhereIF(!string.IsNullOrWhiteSpace(input.RuleName), (it, y) => y.RuleName.Contains(input.RuleName.Trim()))
                         .WhereIF(!string.IsNullOrWhiteSpace(input.UsedDate), it => it.UsedDate.Contains(input.UsedDate.Trim()))
                         .WhereIF(input.Used != null, it => it.Used == input.Used)
                         .Where(exp.ToExpression())
                         .OrderByDescending(it => it.CreateTime)
                         .Select((it, y) => new RulesLogPageOutput
                         {
                             Id = it.Id,
                             RuleCode = it.RuleCode,
                             RuleName = y.RuleName,
                             UsedDate = it.UsedDate,
                             Used = it.Used,
                             CreateOrgId = it.CreateOrgId,
                             CreateUserId = it.CreateUserId,
                             CreateUser = it.CreateUser,
                             CreateTime = it.CreateTime,
                             UpdateUserId = it.UpdateUserId,
                             UpdateUser = it.UpdateUser,
                             UpdateTime = it.UpdateTime,
                             ExtJson = it.ExtJson
                         });
        return query;
    }

    /// <inheritdoc/>
    public async Task<List<RulesLogImportInput>> CheckImport<RulesLogImportInput>(List<RulesLogImportInput> data, bool clearError = false)
    {
        return data;
    }

    #endregion 方法
}
